import Vue from "vue";
var jweixin = require('jweixin-module');

export default {
	
	jweixin,
	
	status:0,

	callbackPool:[],

	maxPoolCount:5,

	nowPoolCount:0,

	snapshot:{},
	
	install(){

		let url = location.href.split('#')[0];
		let params = {
			server: encodeURIComponent(url)
		}

		// Vue.prototype.$request
		Vue.prototype.$request("api/index/get_sign_ature", params).then(res=>{
			console.log(res);
			if(res.code == 1){
				jweixin.config({
					...res.data,
					jsApiList:['scanQRCode','updateAppMessageShareData','updateTimelineShareData'],
					debug: false,
				})
			}
		});
		
		jweixin.ready(()=>{
			console.log('初始化成功 200');
			this.nowPoolCount = 0;
			this.status = 200;
			return this.triggerCallback('resolve');
		});

		jweixin.error((e)=>{
			console.log('微信初始化失败',e);
			this.nowPoolCount++;
			return this.triggerCallback('reject');
		});
	},
	
	// 触发
	triggerCallback(key='resolve'){
		let callbackPool = this.callbackPool;
		console.log('初始化成功');

		if (key === 'resolve') {
			//这里是默认设置的，需要同步修改成 global 通用的 Vue.prototype.$global.
			// this.share({
			// 	title: Vue.prototype.$global.shareTitle,
			// 	desc: Vue.prototype.$global.shareDesc,
			// 	link: Vue.prototype.$global.shareLink,
			// 	imgUrl: Vue.prototype.$global.shareImgUrl,
			// });

			for (let key in this.snapshot) {
				if (this.snapshot.hasOwnProperty(key)) {
					this[key] && this[key].apply(this,this.snapshot[key]);
				}
			}
			this.snapshot = {};
		}
		this.callbackPool = [];
		return callbackPool.map((item)=> item[key] && item[key]());
	},
	
	/* config 是否加载完成 */
	use(){
		console.log("wx share -> status =", this.status);
		return new Promise((resolve, reject)=>{
			if (this.status === 200) {
				return resolve();
			}
			// 如果处于加载中 或者 失败状态触发重新注册
			else {
				this.callbackPool.push({
					resolve,
					reject
				});
				//   if (this.nowPoolCount < this.maxPoolCount) {
					return  this.install();
				//   }
			}
		});
	},
}